package com.getword.service.impl;

import com.getword.domain.Admin;
import com.getword.domain.User;
import com.getword.mongodao.AdminRepository;
import com.getword.mongodao.UserRepository;
import com.getword.service.AdminService;
import com.getword.utils.PathUtil;
import com.getword.web.model.Result;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;


@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Result addAdmin(User user, String token) {
        System.out.println(token);
        user.setRole("ROLE_admin");
        user.setRegisterTime(new Date());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        User save = userRepository.save(user);
        // 头像
        if(StringUtils.isNotBlank(token) && save.getId() != 0){
            String imgPath = PathUtil.basePath + "static/upload/user/images/" + token;
            String destPath = PathUtil.basePath + "static/upload/user/images/" + save.getId();
            try {
                FileUtils.moveFile(new File(imgPath), new File(destPath));
                UpdateResult update = mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(save.getId())),
                        Update.update("image", "/upload/user/images/" + save.getId()), User.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success(save);
//        return null;
    }

    @Override
    public Result login(User user, HttpServletRequest request) {
        User loginUser = userRepository.findByLoginName(user.getLoginName());
        if(loginUser== null){
            return Result.fail("用户名不存在");
        }
        boolean matches = passwordEncoder.matches(user.getPassword(), loginUser.getPassword());
        if(matches){
            String token = UUID.randomUUID().toString();
            request.getSession().setAttribute(token, loginUser);
            return Result.success(new HashMap<String, Object>(){{
                put("token", token);
                put("user", loginUser);
            }});
        }
        return Result.fail("密码错误");

//        Admin query = adminRepository.findAdminByUsername(admin.getUsername());
//        if(query==null){
//            return Result.fail("用户名不存在");
//        }
//        String password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
//        if(query.getPassword().equals(password)){
//            return Result.success(query);
//        }else{
//            return Result.fail("密码错误");
//        }
    }
}
